package com.qiangesoft.im.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qiangesoft.im.auth.UserUtil;
import com.qiangesoft.im.core.constant.ChatTypeEnum;
import com.qiangesoft.im.entity.*;
import com.qiangesoft.im.mapper.ImChatMapper;
import com.qiangesoft.im.pojo.bo.ImChatMessageBO;
import com.qiangesoft.im.pojo.vo.ImChatVO;
import com.qiangesoft.im.pojo.vo.ImMessageVO;
import com.qiangesoft.im.pojo.vo.SysUserVo;
import com.qiangesoft.im.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 聊天 服务实现类
 * </p>
 *
 * @author qiangesoft
 * @date 2024-02-07
 */
@Service
public class ImChatServiceImpl extends ServiceImpl<ImChatMapper, ImChat> implements IImChatService {

    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private IImFriendService friendService;
    @Autowired
    private IImGroupService groupService;
    @Autowired
    private IImGroupUserService groupUserService;
    @Autowired
    private IImMessageService messageService;

    @Override
    public void removeChat(Long id) {
        LambdaUpdateWrapper<ImChat> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(ImChat::getId, id)
                .set(ImChat::getDelFlag, true);
        baseMapper.update(null, updateWrapper);
    }

    @Override
    public List<ImChatVO> listChat() {
        List<ImChatVO> groupVOList = new ArrayList<>();

        Long userId = UserUtil.getUserId();
        List<ImChat> chatList = baseMapper.listChat(userId);
        if (CollectionUtils.isEmpty(chatList)) {
            return groupVOList;
        }

        // 聊天列表对象信息
        List<Long> friendIdList = chatList.stream().filter(e -> ChatTypeEnum.PERSON.getCode().equals(e.getChatType())).map(ImChat::getTargetId).collect(Collectors.toList());
        Map<Long, ImFriend> friendMap = new HashMap<>();
        Map<Long, SysUser> sysUserMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(friendIdList)) {
            List<ImFriend> friendList = friendService.listByIds(friendIdList);
            friendMap = friendList.stream().collect(Collectors.toMap(ImFriend::getId, imFriend -> imFriend));
            List<Long> friendUserIdList = friendList.stream().map(ImFriend::getFriendUserId).collect(Collectors.toList());
            sysUserMap = sysUserService.listByIds(friendUserIdList).stream().collect(Collectors.toMap(SysUser::getId, sysUser -> sysUser));
        }
        List<Long> groupIdList = chatList.stream().filter(e -> ChatTypeEnum.GROUP.getCode().equals(e.getChatType())).map(ImChat::getTargetId).collect(Collectors.toList());
        Map<Long, ImGroup> groupMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(groupIdList)) {
            groupMap = groupService.listByIds(groupIdList).stream().collect(Collectors.toMap(ImGroup::getId, imGroup -> imGroup));
        }

        // 未读消息
        List<Long> chatIdList = chatList.stream().map(ImChat::getId).collect(Collectors.toList());
        List<ImChatMessageBO> unReadMessageList = messageService.listChatUnreadMessage(userId, chatIdList);
        // 最新消息
        List<ImMessage> latestMessageList = messageService.listLatestMessage(userId, chatIdList);
        List<Long> friendChatIdList = chatList.stream().filter(e -> ChatTypeEnum.PERSON.getCode().equals(e.getChatType())).map(ImChat::getId).collect(Collectors.toList());
        List<Long> groupChatIdList = chatList.stream().filter(e -> ChatTypeEnum.GROUP.getCode().equals(e.getChatType())).map(ImChat::getId).collect(Collectors.toList());
        List<ImMessage> friendLatestMessageList = latestMessageList.stream().filter(e -> friendChatIdList.contains(e.getChatId())).collect(Collectors.toList());
        List<ImMessage> groupLatestMessageList = latestMessageList.stream().filter(e -> groupChatIdList.contains(e.getChatId())).collect(Collectors.toList());

        // 昵称
        List<Long> sendFriendIdList = friendLatestMessageList.stream().map(ImMessage::getSenderId).collect(Collectors.toList());
        Map<Long, String> remarkMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(sendFriendIdList)) {
            LambdaQueryWrapper<ImFriend> fqueryWrapper = new LambdaQueryWrapper<>();
            fqueryWrapper.eq(ImFriend::getUserId, userId)
                    .in(ImFriend::getFriendUserId, sendFriendIdList);
            remarkMap = friendService.list(fqueryWrapper).stream().collect(Collectors.toMap(ImFriend::getFriendUserId, ImFriend::getRemark));
        }
        List<Long> sendGroupIdList = groupLatestMessageList.stream().map(ImMessage::getSenderId).collect(Collectors.toList());
        Map<Long, String> nicknameMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(groupIdList) && !CollectionUtils.isEmpty(sendGroupIdList)) {
            LambdaQueryWrapper<ImGroupUser> gqueryWrapper = new LambdaQueryWrapper<>();
            gqueryWrapper.in(ImGroupUser::getGroupId, groupIdList)
                    .in(ImGroupUser::getUserId, sendGroupIdList);
            nicknameMap = groupUserService.list(gqueryWrapper).stream().collect(Collectors.toMap(ImGroupUser::getUserId, ImGroupUser::getNickName));
        }

        for (ImChat chat : chatList) {
            ImChatVO vo = new ImChatVO();
            vo.setId(chat.getId());
//            vo.setAvatar(avatarMap.get());
            Long targetId = chat.getTargetId();
            String chatType = chat.getChatType();
            vo.setTargetId(targetId);
            vo.setChatType(chatType);

            // 未读消息数
            Optional<ImChatMessageBO> first = unReadMessageList.stream().filter(e -> e.getChatId().equals(chat.getId())).findFirst();
            Integer unreadNum = first.isPresent() ? first.get().getUnreadNum() : 0;
            vo.setUnreadNum(unreadNum);

            String name;
            String avatar;
            if (ChatTypeEnum.PERSON.getCode().equals(chatType)) {
                ImFriend friend = friendMap.get(targetId);
                name = friend.getRemark();
                SysUser sysUser = sysUserMap.get(friend.getFriendUserId());
                avatar = sysUser.getAvatar();

                Optional<ImMessage> firstLatest = friendLatestMessageList.stream().filter(e -> e.getChatId().equals(chat.getId())).findFirst();
                if (firstLatest.isPresent()) {
                    ImMessage message = firstLatest.get();
                    ImMessageVO messageVO = new ImMessageVO();
                    messageVO.setId(message.getId());
                    messageVO.setMessageType(message.getMessageType());
                    messageVO.setMessage(message.getMessage());
                    messageVO.setReadFlag(false);
                    messageVO.setSendTime(message.getCreateTime());

                    // 发送人
                    SysUserVo sysUserVo = new SysUserVo();
                    Long senderId = message.getSenderId();
                    sysUserVo.setId(senderId);
                    sysUserVo.setNickName(remarkMap.get(senderId));
                    messageVO.setSender(sysUserVo);
                    vo.setLatestMessage(messageVO);
                }
            } else {
                ImGroup group = groupMap.get(targetId);
                name = group.getName();
                avatar = group.getAvatar();

                Optional<ImMessage> firstLatest = groupLatestMessageList.stream().filter(e -> e.getChatId().equals(chat.getId())).findFirst();
                if (firstLatest.isPresent()) {
                    ImMessage message = firstLatest.get();
                    ImMessageVO messageVO = new ImMessageVO();
                    messageVO.setId(message.getId());
                    messageVO.setMessageType(message.getMessageType());
                    messageVO.setMessage(message.getMessage());
                    messageVO.setReadFlag(false);
                    messageVO.setSendTime(message.getCreateTime());

                    // 发送人
                    SysUserVo sysUserVo = new SysUserVo();
                    Long senderId = message.getSenderId();
                    sysUserVo.setId(senderId);
                    sysUserVo.setNickName(nicknameMap.get(senderId));
                    messageVO.setSender(sysUserVo);
                    vo.setLatestMessage(messageVO);
                }
            }
            vo.setName(name);
            vo.setAvatar(avatar);
            groupVOList.add(vo);
        }
        return groupVOList;
    }

    @Override
    public void setTop(Long id) {
        LambdaUpdateWrapper<ImChat> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(ImChat::getId, id)
                .set(ImChat::getTopFlag, true);
        baseMapper.update(null, updateWrapper);
    }

    @Override
    public void cancelTop(Long id) {
        LambdaUpdateWrapper<ImChat> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(ImChat::getId, id)
                .set(ImChat::getTopFlag, false);
        baseMapper.update(null, updateWrapper);
    }

}
